﻿using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;

namespace Framework.Core.Dependency.Adapter
{
    public static class SerializeHelper
    {
        public static void Serialize<T>(this IEnumerable<T> projects, string filePath)
        {
            var settings = new XmlWriterSettings { Indent = true };

            using (var stream = XmlWriter.Create(filePath, settings))
            {
                var serializer = new DataContractSerializer(typeof(IEnumerable<T>));

                serializer.WriteObject(stream, projects);
            }
        }

        private static IEnumerable<T> Deserialize<T>(this Stream stream)
        {
            using (stream)
            {
                var serializer = new DataContractSerializer(typeof(IEnumerable<T>));

                return (IEnumerable<T>)serializer.ReadObject(stream);
            }
        }

        public static IEnumerable<T> Deserialize<T>(this string filePath)
        {
            using (var fs = File.Open(filePath, FileMode.Open, FileAccess.Read))
            {
                return Deserialize<T>(fs);
            }
        }
    }
}